package com.yunji.generate.util;


import com.yunji.generate.common.ResultMessage;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Locale;
import java.util.Map;

public class FreemarkerUtil {

    private static final Logger LOG = LoggerFactory.getLogger(FreemarkerUtil.class);
    private static final String DEFAULT_ENCODING = "UTF-8";

    private FreemarkerUtil() {
    }

    public static ResultMessage render(String templateFile, Map<String, Object> context, String outFilePath) {
        Writer writer = null;
        try {
            LOG.info("context is [" + context + " ],templateFile is[" + templateFile + "],outFilePath is" + outFilePath);
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
            configuration.setEncoding(Locale.CHINA, DEFAULT_ENCODING);
            TemplateLoader templateLoader = new ClassTemplateLoader((ClassLoader) null, "/");
            configuration.setTemplateLoader(templateLoader);
            Template template = configuration.getTemplate(templateFile);
            File file = new File(outFilePath);
            if (file.exists()) {
                LOG.info(outFilePath + " has exists!");
                boolean flag = file.delete();
                LOG.info(outFilePath + " delete !" + (flag ? "success" : "fail"));
            }
            FileUtils.touch(file);
            writer = new OutputStreamWriter(new FileOutputStream(file), DEFAULT_ENCODING);
            template.process(context, writer);
            return ResultMessage.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.fail(e.getMessage());
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(), e);
                    e.printStackTrace();
                }
            }
        }
    }
}
